#include <etcd/Client.hpp>
#include <etcd/Watcher.hpp>
void callback(etcd::Response resp) {
    if(!resp.is_ok()) {
        std::cerr << "Watcher failed: " << resp.error_message() << std::endl;
        return;
    }

    for(const auto& ev :resp.events()) {
        if(ev.event_type() == etcd::Event::EventType::PUT) {
            std::cout << "previous key: " << ev.prev_kv().key() << std::endl;
            std::cout << "previous value: " << ev.prev_kv().as_string() << std::endl;
            std::cout << "current key: " << ev.kv().key() << std::endl;
            std::cout << "current value: " << ev.kv().as_string() << std::endl;
        }
        else if(ev.event_type() == etcd::Event::EventType::DELETE_) {
            std::cout << "deleted key: " << ev.kv().key() << std::endl;
            std::cout << "deleted value: " << ev.kv().as_string() << std::endl;
        }
        else {
            std::cout << "unknown event type" << std::endl;
        }
    }
}
int main() {
    std::string addr = "http://127.0.0.1:2379";
    etcd::Client client(addr);
    auto resp = client.ls("/service").get();
    if(!resp.is_ok())
    {
        std::cerr << "Failed to get key: " << resp.error_message() << std::endl;
        return 1;
    }
    int sz = resp.keys().size();
    std::cout << sz << std::endl;
    for(int i = 0; i < sz; ++i)
    {
        std::cout << "key: " << resp.key(i) << std::endl;
        std::cout << "value: " << resp.value(i).as_string() << endl;
    }
    
    // etcd::Watcher watcher(client, "/server", callback, true);
    // std::this_thread::sleep_for(std::chrono::seconds(30));
    // 在另一个线程中停止 Watcher
    // std::thread cancel_thread([&watcher]() {
    //     std::this_thread::sleep_for(std::chrono::seconds(7)); // 等待10秒
    //     std::cout << "Stopping watcher..." << std::endl;
    //     watcher.Cancel(); // 停止等待
    // });
    // watcher.Wait();
    // cancel_thread.join(); // 等待取消线程结束
    return 0;
}